package com.gjp.netty.handler;

import com.gjp.netty.config.NettyConfig;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;

import java.util.Date;

/**
 * Created by 郭金鹏 on 2018/2/27.
 * <p>
 * 接收/处理/响应客户端websocket请求的核心处理器
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler {

    private WebSocketServerHandshaker handshaker;
    private static final String WEB_SOCKET_URL = "ws://localhost:8888/websocket";

    //建立连接时-调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //super.channelActive(ctx);
        NettyConfig.group.add(ctx.channel());
        System.out.println("客户端与服务端建立连接.");
    }

    //断开连接时-调用
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //super.channelInactive(ctx);
        NettyConfig.group.remove(ctx.channel());
        System.out.println("客户端与服务端断开连接.");
    }

    //接收客户端数据结束后-调用
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //super.channelReadComplete(ctx);
        ctx.flush();
    }

    //出现异常时调用
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }


    //服务端处理客户端websocket请求的核心方法
    protected void channelRead0(ChannelHandlerContext context, Object msg) throws Exception {
        //判断这个msg消息 是否是http连接请求
        if (msg instanceof FullHttpRequest) {
            handHttpRequest(context, (FullHttpRequest) msg);

            //判断是否是websocket连接请求
        } else if (msg instanceof WebSocketFrame) {
            handWebSocketRequest(context, (WebSocketFrame) msg);
        }
    }

    //处理http连接请求
    private void handHttpRequest(ChannelHandlerContext context, FullHttpRequest request) {
        //如果不是http请求
        if (!request.decoderResult().isSuccess()
                || !("websocket").equals(request.headers().get("Upgrade"))) {
            sendHttpResponse(context, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        //是http请求
        WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(WEB_SOCKET_URL, null, false);
        handshaker = factory.newHandshaker(request);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(context.channel());
        } else {
            handshaker.handshake(context.channel(), request);
        }
    }

    //向客户端响应消息
    private void sendHttpResponse(ChannelHandlerContext context, FullHttpRequest request, DefaultFullHttpResponse response) {
        if (response.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(response.status().toString(), CharsetUtil.UTF_8);
            response.content().writeBytes(buf);
            buf.release();
        }
        //向客户端发送数据
        ChannelFuture future = context.channel().writeAndFlush(response);
        if (response.status().code() != 200) {
            //关闭连接
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    //处理websocket连接请求
    private void handWebSocketRequest(ChannelHandlerContext context, WebSocketFrame frame) {
        //是否是关闭websocket的命令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(context.channel(), (CloseWebSocketFrame) frame.retain());
        }
        //是否是ping消息
        if (frame instanceof PingWebSocketFrame) {
            //回复pong
            context.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        //判断是否是二进制消息，是就抛出异常
        if (!(frame instanceof TextWebSocketFrame)) {
            System.out.println("不支持二进制消息");
            throw new RuntimeException("不支持二进制消息");
        }

        //返回应答消息
        //获取客户端发送的消息
        String clientData = ((TextWebSocketFrame) frame).text();
        System.out.println("收到客户端消息：" + clientData);
        TextWebSocketFrame twf = new TextWebSocketFrame(new Date().toString()
                + context.channel().id()
                + "====>>>"
                + clientData);
        //将客户端的消息，群发到所有在线的客户端
        NettyConfig.group.writeAndFlush(twf);
    }
}
